package com.zhongkun.datahome.service.res.appointment;

import com.zhongkun.datahome.common.utils.bean.BeanConverter;
import com.zhongkun.datahome.service.domain.Appointment;
import com.zhongkun.datahome.service.domain.AppointmentTimeSlot;
import io.jsonwebtoken.lang.Collections;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author huangjie
 * @since 2025/6/26
 */
@Data
public class AppointmentExportVo extends Appointment {

    @ApiModelProperty("楼栋信息")
    private String appointmentHouseInfo;

    private List<AppointmentTimeSlotExportVo> appointmentTimeSlotExportVoList;

    public static List<AppointmentExportVo> build(List<AppointmentVo> appointmentVoList, List<AppointmentTimeSlot> appointmentTimeSlotList, List<AppointmentRecordVo> appointmentRecordVoList) {
        List<AppointmentExportVo> appointmentExportVoList = new ArrayList<>();

        Map<Long, List<AppointmentTimeSlot>> slotMap = appointmentTimeSlotList.stream().collect(Collectors.groupingBy(AppointmentTimeSlot::getAppointmentId));
        Map<Long, List<AppointmentRecordVo>> recordSlotMap = appointmentRecordVoList.stream().collect(Collectors.groupingBy(AppointmentRecordVo::getTimeSlotId));

        for (AppointmentVo appointmentVo : appointmentVoList) {
            AppointmentExportVo appointmentExportVo = BeanConverter.copyBean(AppointmentExportVo.class, appointmentVo);
            List<AppointmentTimeSlot> appointmentTimeSlotItemList = slotMap.get(appointmentExportVo.getId());

            List<AppointmentTimeSlotExportVo> appointmentTimeSlotExportVoList = AppointmentTimeSlotExportVo.build(appointmentTimeSlotItemList, recordSlotMap);
            appointmentExportVo.setAppointmentTimeSlotExportVoList(appointmentTimeSlotExportVoList);
            appointmentExportVoList.add(appointmentExportVo);
        }

        // 就是排序，兼容一些null的场景
        appointmentExportVoList.sort(
                Comparator.nullsLast(
                        Comparator.comparing(
                                x -> Optional.ofNullable(x.getAppointmentTimeSlotExportVoList())
                                        .filter(list -> !list.isEmpty())
                                        .map(list -> list.get(0))
                                        .map(AppointmentTimeSlotExportVo::getTimeSlotDate)
                                        .orElse(null),
                                Comparator.nullsLast(Comparator.naturalOrder()) // 处理 timeSlotDate 为 null
                        )
                )
        );

        return appointmentExportVoList;
    }
}
